package com.yocard.yxyd.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.webkit.ValueCallback;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.barlibrary.ImmersionBar;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.yocard.yxyd.R;
import com.yocard.yxyd.adapter.OrderFragmentAdapter;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.base.GlideApp;
import com.yocard.yxyd.http.model.request.OrderListRequest;
import com.yocard.yxyd.http.model.response.BannerBean;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.ui.activity.InviteFriendsActivity;
import com.yocard.yxyd.ui.activity.WebViewActivity;
import com.yocard.yxyd.ui.contract.OrderContract;
import com.yocard.yxyd.ui.fragment.base.BaseBackFragment;
import com.yocard.yxyd.ui.presenter.OrderPresenter;
import com.yocard.yxyd.ui.view.OrderDrawerView;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.CacheDoubleStaticUtils;
import com.yocard.yxyd.utils.util.KeyboardUtils;
import com.yocard.yxyd.utils.util.SPUtils;
import com.yocard.yxyd.utils.util.SizeUtils;
import com.yocard.yxyd.utils.util.StringUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.db.DBManager;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.yocard.yxyd.event.EventCode.REFRESH_BANNER;
import static com.yocard.yxyd.event.EventCode.REFRESH_ORDER_LIST;

/**
 * Created on 2019/4/2.
 */
public class OrderFragment extends BaseBackFragment<OrderPresenter> implements OrderContract.View {

    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_switch)
    TextView tvSwitch;
    @BindView(R.id.tab_layout)
    SmartTabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.drawer)
    OrderDrawerView drawerView;
    @BindView(R.id.rl_head_layout)
    RelativeLayout rlHeadLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.top_bg)
    View topBg;
    protected int headHeight;
    protected AMapLocationClient mLocationClient;
    String currentCityCode;
    boolean isSwichLocation;
    @BindView(R.id.vp_banner)
    com.zhouwei.mzbanner.MZBannerView vpBanner;
    private List<ValueCallback<String>> locationListeners = new ArrayList<>();
    protected OrderFragmentAdapter mAdapter;
    List<Integer> testBanner;
    int currentTabIndex = 0;
    BannerBean bannerBean;
    private boolean bannerScrolled;

    @Override
    protected int getLayoutId() {
        return R.layout.ft_order;
    }

    @Override
    protected void initEventAndData() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColorInt(Color.BLACK)
                .navigationBarColorInt(Color.BLACK)
                .autoDarkModeEnable(true, 0.2f)
                .init();

        currentCityCode = CacheDoubleStaticUtils.getString(Constants.KEY_CITY_CODE, "");
        tvLocation.setText(CacheDoubleStaticUtils.getString(Constants.KEY_CITY_NAME, "未定位"));
        initViewPager();
        initDrawer();
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
                int scrollHeight = vpBanner.getHeight();
                boolean scrolled = true;
                if (offset + scrollHeight > SizeUtils.dp2px(0)) {
                    scrolled = false;
                }
                if (scrolled ^ bannerScrolled) {
                    if (scrolled) {
                        showWhiteActionBar();
                    } else {
                        showPrimaryActionBar();
                    }
                    bannerScrolled = scrolled;
                }
            }
        });
        isSwichLocation = false;
        mPresenter.initLocation();
        mPresenter.getBanners();
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); //关闭手势滑动
    }

    private void showWhiteActionBar() {
        topBg.setBackgroundColor(getResources().getColor(R.color.white));
        tvSwitch.setTextColor(getResources().getColor(R.color.light_yellow));
        tvLocation.setTextColor(getResources().getColor(R.color.color_4a4a4a));
        tvTitle.setTextColor(getResources().getColor(R.color.color_4a4a4a));
        tvSwitch.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_yellow_switch, 0);
        tvLocation.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_yellow_triangle, 0);
    }

    private void showPrimaryActionBar() {
        topBg.setBackgroundResource(R.drawable.shape_order_head_bg);
        tvSwitch.setTextColor(getResources().getColor(R.color.white));
        tvSwitch.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_white_switch, 0);
        tvLocation.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_white_triangle, 0);
        tvLocation.setTextColor(getResources().getColor(R.color.white));
        tvTitle.setTextColor(getResources().getColor(R.color.white));
    }


    private void initDrawer() {
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {
                KeyboardUtils.hideSoftInput(getActivity());

            }

            @Override
            public void onDrawerOpened(@NonNull View view) {

            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
            }

            @Override
            public void onDrawerStateChanged(int i) {

            }
        });
    }

    private void initViewPager() {

        rlHeadLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                headHeight = rlHeadLayout.getHeight();
                rlHeadLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

        ViewGroup.LayoutParams layoutParams = rlHeadLayout.getLayoutParams();
        ValueCallback<Integer> callback = new ValueCallback<Integer>() {
            @Override
            public void onReceiveValue(Integer value) {
                layoutParams.height = headHeight + value;
                rlHeadLayout.requestLayout();
            }
        };
        mAdapter = new OrderFragmentAdapter(getChildFragmentManager(), callback);
        viewPager.setAdapter(mAdapter);
        tabLayout.setViewPager(viewPager);
        viewPager.setOffscreenPageLimit(5);
        tabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                ((TextView) tabLayout.getTabAt(currentTabIndex)).setTextSize(14);
                ((TextView) tabLayout.getTabAt(i)).setTextSize(16);
//                ((TextView) tabLayout.getTabAt(i)).setTextColor(getResources().getColor(R.color.white));
                currentTabIndex = i;
                Fragment fragmentAt = mAdapter.getFragmentAt(currentTabIndex);
                if (fragmentAt instanceof OrderListFragment) {
                    OrderListFragment fragment = (OrderListFragment) fragmentAt;
                    fragment.refresh();
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        ((TextView) tabLayout.getTabAt(0)).setTextSize(16);
//        ((TextView) tabLayout.getTabAt(currentTabIndex)).setTextSize(18);
        vpBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int i) {
                if (bannerBean == null || bannerBean.getList() == null || bannerBean.getList().size() == 0) {
                    return;
                }
                String url = bannerBean.getList().get(i).getTarget_url();
                if (TextUtils.isEmpty(url)) {
                    return;
                }
                if (url.startsWith("youdan://appview")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return;
                }
//                CommonUtils.openBroswer(mContext, url);
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                bundle.putString("title", bannerBean.getList().get(i).getTitle());
                ActivityUtils.startActivity(bundle, WebViewActivity.class);
            }
        });
    }

    public static class BannerViewHolder implements MZViewHolder<BannerBean.ListBean> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, BannerBean.ListBean data) {
            // 数据绑定
//            Glide4Engine.getInstance().loadImage(context, data.getImg_url(), mImageView);
            GlideApp.with(context).load(data.getImg_url()).apply(RequestOptions.bitmapTransform(new RoundedCorners(20))).into(mImageView);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        vpBanner.pause();//暂停轮播
    }

    @Override
    public void onResume() {
        super.onResume();
        vpBanner.start();//开始轮播
    }

    @OnClick({R.id.tv_location, R.id.tv_switch})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_location:
                isSwichLocation = true;
                mPresenter.switchCity(pickListener, getActivity());
                break;
            case R.id.tv_switch:
                drawerLayout.openDrawer(drawerView);
                break;
        }
    }


    @Override
    public void getBanners(BannerBean bannerBean) {
        this.bannerBean = bannerBean;
        vpBanner.setPages(bannerBean.getList(), new MZHolderCreator() {
            @Override
            public MZViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
        vpBanner.start();//开始轮播
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden && drawerLayout.isDrawerOpen(drawerView)) {
            drawerLayout.closeDrawer(drawerView);
        }
    }

    public void setSelectCallback(ValueCallback<OrderListRequest> requestValueCallback) {
        drawerView.setSelectListener(requestValueCallback);
    }

    public void setLocationListener(ValueCallback<String> locationListener) {
        locationListeners.add(locationListener);
    }

    public void closeDrawer() {
        drawerLayout.closeDrawer(drawerView);
    }

    @Override
    public boolean onBackPressed() {
        if (drawerLayout.isDrawerOpen(drawerView)) {
            closeDrawer();
            return true;
        }
        return false;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void onLocationInit(AMapLocationClient locationClient) {
        if (mLocationClient == null) {
            DBManager dbManager = new DBManager(mContext);
            mLocationClient = locationClient;
            mLocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation location) {
                    String city = location.getCity();
                    SPUtils.getInstance().put(Constants.KEY_LONGITUDE, String.valueOf(location.getLongitude()));
                    SPUtils.getInstance().put(Constants.KEY_LATITUDE, String.valueOf(location.getLatitude()));

                    if (StringUtils.isEmpty(city)) {
                        ToastUtils.showLong("定位获取城市失败！");
                        return;
                    }

                    List<City> cities = dbManager.searchCity(city);
                    if (cities != null && cities.size() > 0) {
                        City seachCity = cities.get(0);

                        if (isSwichLocation) {
                            CityPicker.from(getActivity()).locateComplete(new LocatedCity(seachCity.getName()
                                    , seachCity.getCode()), LocateState.SUCCESS);
                        } else {
                            tvLocation.setText(seachCity.getName());
                            currentCityCode = seachCity.getCode();
                            String cityCode = CacheDoubleStaticUtils.getString(Constants.KEY_CITY_CODE, "");
                            if (!currentCityCode.equals(cityCode)) {
                                if (locationListeners != null && locationListeners.size() > 0) {
                                    for (ValueCallback<String> callback : locationListeners) {
                                        callback.onReceiveValue(currentCityCode);
                                    }
                                }
                            }
                        }

                        CacheDoubleStaticUtils.put(Constants.KEY_CITY_CODE, seachCity.getCode());
                        CacheDoubleStaticUtils.put(Constants.KEY_CITY_NAME, seachCity.getName());
                    }
                }
            });
        }
        mLocationClient.startLocation();
    }

    OnPickListener pickListener = new OnPickListener() {
        @Override
        public void onPick(int i, City city) {
            tvLocation.setText(city.getName());
            currentCityCode = city.getCode();
            CacheDoubleStaticUtils.put(Constants.KEY_CITY_CODE, currentCityCode);
            CacheDoubleStaticUtils.put(Constants.KEY_CITY_NAME, city.getName());
            if (locationListeners != null && locationListeners.size() > 0) {
                for (ValueCallback<String> callback : locationListeners) {
                    callback.onReceiveValue(currentCityCode);
                }
            }
        }

        @Override
        public void onLocate() {
            if (mLocationClient == null) {
                mPresenter.initLocation();
            } else {
                onLocationInit(mLocationClient);
            }
        }

        @Override
        public void onCancel() {

        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }

    }

    public String getCurrentCityCode() {
        return currentCityCode;
    }

    public void scrollCurrentFragmentTop() {
        Fragment fragmentAt = mAdapter.getFragmentAt(viewPager.getCurrentItem());
        if (fragmentAt instanceof OrderListFragment) {
            OrderListFragment fragment = (OrderListFragment) fragmentAt;
            fragment.scrollTop();
        }
    }

    public void setIcoSelect(boolean select) {
        tvSwitch.setSelected(select);
    }

    public boolean getIcoSelectStatus() {
        return tvSwitch.isSelected();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFreshEvent(CommonBean bean) {
        if (bean.getCode() == REFRESH_ORDER_LIST) {
            Fragment fragmentAt = mAdapter.getFragmentAt(viewPager.getCurrentItem());
            if (fragmentAt instanceof OrderListFragment) {
                OrderListFragment fragment = (OrderListFragment) fragmentAt;
                fragment.refresh();
            }
//            mPresenter.getBanners();
        } else if (bean.getCode() == REFRESH_BANNER) {
            mPresenter.getBanners();
        }
    }

}
